package cn.rmc.hrm.service.impl;


import cn.rmc.hrm.doc.CourseDoc;
import cn.rmc.hrm.doc.dto.CourseSearchDto;
import cn.rmc.hrm.esmapper.HighlightResultMapper;
import cn.rmc.hrm.repository.CourseRepositoryEs;
import cn.rmc.hrm.service.ICourseEsSearch;
import cn.rmc.hrm.util.PageList;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class CourseEsSearchImpl implements ICourseEsSearch {
    @Autowired
    private CourseRepositoryEs courseRepositoryEs;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private HighlightResultMapper highlightResultMapper;

    @Override
    public PageList<CourseDoc> searchCourse(CourseSearchDto dto) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
//        查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(StringUtils.hasLength(dto.getKeyword())){
//            查询名字或者店铺名
            boolQuery.must(QueryBuilders.multiMatchQuery(dto.getKeyword(),"name","tenantName"));
        }
//        课程类型
        if(dto.getCourseTypeId() != null){
            boolQuery.filter(QueryBuilders.termQuery("courseTypeId",dto.getCourseTypeId()));
        }
//        最小价格
        if(dto.getPriceMin() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(dto.getPriceMin()));
        }
//        最大价格
        if(dto.getPriceMax() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(dto.getPriceMax()));
        }
        if(StringUtils.hasLength(dto.getGradeName())){
            boolQuery.filter(QueryBuilders.termQuery("gradeName",dto.getGradeName()));
        }
        //设置查询query
        //设置内容高亮显示
        HighlightBuilder.Field field = new HighlightBuilder.Field("name").preTags("<font style='color:orange'><b>").postTags("</b></font>");
        // 名字高亮
        builder.withHighlightFields(field);
        builder.withQuery(boolQuery);
        //排序字段
        if(StringUtils.hasLength(dto.getSortField())){
            String filedName = "startTime";
            switch (dto.getSortField().toLowerCase()){
                case "xl": filedName = "saleCount";break;
                case "xp": filedName = "startTime";break;
                case "pl": filedName = "commentCount";break;
                case "jg": filedName = "price";break;
                case "rq": filedName = "viewCount";break;
                default:filedName = "startTime";break;
            }
//            排序
            SortOrder sortOrder = SortOrder.DESC;
            if(dto.getSortType().equals("asc")){
                sortOrder = SortOrder.ASC;
            }
            builder.withSort(new FieldSortBuilder(filedName).order(sortOrder));
        }
        builder.withPageable(PageRequest.of(dto.getPage() -1, dto.getRows()));
        AggregatedPage<CourseDoc> page = elasticsearchTemplate.queryForPage(builder.build(),CourseDoc.class,highlightResultMapper);
        //将 Page  转换成PageList并返回 getTotalElements()总条数 page.getContent())当前页的数据
        return new PageList<>( page.getTotalElements(), page.getContent());
    }
}
